/*
 * Copyright (C) 2012 Shuhrat Dehkanov
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package uz.efir.android.sms;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.SmsMessage;
import android.text.format.DateFormat;
import android.util.Log;

public class SmsListener extends BroadcastReceiver {
    private static final String TAG = "SMS2HTTPPOST";

    @Override
    public void onReceive(Context context, Intent intent) {

        Map<String, ?> map = PreferenceManager.
                getDefaultSharedPreferences(context).getAll();
        if (map.isEmpty()) {
            Log.d(TAG, "Options are not set yet...");
            // The user has not set up the options,
            // direct them to there
            Intent options = new Intent(Intent.ACTION_MAIN);
            options.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            options.putExtra(TAG, true); // This is for future use
            options.setClass(context, Options.class);
            context.startActivity(options);
            return;
        }
        final String url = (String) map.get("post_url_key");
        Log.i(TAG, "URL to post: " + url); //TODO: Temporary log, remove later

        Bundle extras = intent.getExtras();
        if (extras == null) {
            Log.e(TAG, "Got SMS_RECEIVED intent with null bundle extras");
            return;
        }

        Log.i(TAG, "Started processing incoming SMS...");

        Object[] pdus = (Object[]) extras.get("pdus");
        for (int i = 0; i < pdus.length; i++) {
            SmsMessage message = SmsMessage.createFromPdu((byte[]) pdus[i]);

            final Map<String, String> sms = new LinkedHashMap<String, String>();
            sms.clear();
            sms.put("from", message.getOriginatingAddress());
            sms.put("date", DateFormat.format("yyyyMMddhhmmss",
                    message.getTimestampMillis()).toString());
            sms.put("text", message.getMessageBody());

            final HttpRequest request = new HttpRequest();

            new Thread(new Runnable() {
                public void run () {
                    try {
                        request.sendPost(new URL(url), sms);
                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        Log.i(TAG, "Done!");
    }
}